<template>
    <div class="goodList">
        <!-- 退出 -->
        <img class="exitBtn" @click="exitBtn" src="../assets/img/exitBtn.png" alt="">
        <!-- 内容 -->
        <div class="conlist">
            <div class="mainBox">
                <div class="btns" @click="clickChangeBtn('left')">
                    <img src="../assets/img/leftQh.png" alt="">
                </div>
                <div class="mainImg">
                    <el-carousel ref="carousel" height="100%" :autoplay="false">
                        <el-carousel-item v-for="(item,index) in list" :key="index" >
                            <div>
                                <div class="imgBox">
                                    <img :src="item.imgUrl" alt="">
                                </div>
                                <div class="texts">
                                    <div class="name FONT">
                                        <div class="ju"></div>
                                        <span>{{item.name}}</span>
                                    </div>
                                    <span class="price FONT">￥{{item.sellingPrice}}</span>
                                </div>
                                <div class="toBuy FONT" @click="clickGoods(item)">去支付</div>
                            </div>
                        </el-carousel-item>
                    </el-carousel>
                </div>
                <div class="btns" @click="clickChangeBtn('right')">
                    <img src="../assets/img/rightQh.png" alt="">
                </div>
            </div>
            <div class="listBox" v-if="list.length > 0">
                <div class="list" id="list" v-rollX v-clickRoll>
                    <div class="items" v-for="(item,index) in list" :data-index="index" :key="index">
                        <div class="imgBox">
                            <img :src="item.imgUrl" alt="">
                        </div>
                        <div class="texts">
                            <div class="name FONT">
                                <div class="ju"></div>
                                <span>{{item.name}}</span>
                            </div>
                            <div class="price FONT">￥{{item.sellingPrice}}</div>
                        </div>
                        <transition name="el-fade-in-linear">
                            <img v-show="actives.name == item.name" class="sanjiao" src="../assets/img/loadingIcon.png" alt="">
                        </transition>
                    </div>
                </div>
            </div>
        </div>
        <!-- 支付弹框 -->
        <paymentPopUp :isShow.sync="paymentShow" :qrCode="qrCode" :goodInfo="goodInfo" @paymentSuccess="paymentSuccess"></paymentPopUp>
    </div>
</template>

<script>
import heads from '../components/heads.vue'
import paymentPopUp from '../components/paymentPopUp.vue'
import {prodList,orderConfirm,orderSubmit,bodyEmitter,sseResult} from '../server/api'
import QRCode from "qrcode"
import { mapMutations } from 'vuex'
import { EventSourcePolyfill } from "event-source-polyfill";
import { fetchEventSource } from '@microsoft/fetch-event-source'; 
import {mapState} from 'vuex'
export default {
    computed:{
        ...mapState([
            //必须带引号
            'token'
        ])
    },
    components:{
        heads,
        paymentPopUp,
    },
    directives:{
        // 列表滚动区域点击
        clickRoll:{
            // 指令的定义
            bind:(el, binding, vnode)=> {
                let itemsArr = [...el.getElementsByClassName('items')];
                itemsArr.forEach(element => {
                    element.addEventListener('click',(evenet)=>{
                        let isClick = el.getAttribute('data-flag')
                        if(isClick === 'true'){
                            let index = element.getAttribute('data-index')
                            let that = vnode.context;
                            // 设置轮播图滚动
                            that.$refs.carousel.setActiveItem(index)
                            // 设置列表滚动
                            let offsetLeft =itemsArr[index].offsetLeft;
                            list.scrollTo({left: offsetLeft - 2, top: 0, behavior: 'smooth'})
                            // 设置当前选中
                            that.actives = that.list[index];
                            // /选中的index
                            that.activeIndex = index;
                        }
                    })
                });
            }
        }
    },
    data(){
        return {
            // 模型id
            modelId:'',
            // 展示标题
            title:'',
            // 列表数据
            list:[],
            // 选中的
            actives:{},
            // 选中的index
            activeIndex:0,
            // 购买弹框(支付)
            paymentShow:false,
            // 选择的商品信息
            goodInfo:{},
            // 生成支付的二维码
            qrCode:'',
            // 生成的任务id
            taskId:'',
            // 生成订单的订单号
            orderNumber:'',
            // 定时器
            interval:null,
        }
    },
    methods:{
        ...mapMutations([
            'setCommonData'
        ]),
        // 点击轮播图切换按钮
        clickChangeBtn(type){
            let carousel = this.$refs.carousel;
            if(type == 'left'){
                // 点击左侧
                carousel.prev();
                // 判断是否是第一个
                if(this.activeIndex == 0){
                    // 是第一个
                    this.activeIndex = this.list.length - 1
                    this.actives = this.list[this.activeIndex];
                }else{
                    // 不是第一个
                    this.activeIndex = Number(this.activeIndex)-1
                    this.actives = this.list[this.activeIndex];
                }
            }else{
                // 点击右侧
                carousel.next();
                // 判断是否是最后一个
                if(this.activeIndex == this.list.length - 1){
                    // 是最后一个
                    this.activeIndex = 0
                    this.actives = this.list[this.activeIndex];
                }else{
                    // 不是最后一个
                    this.activeIndex = Number(this.activeIndex)+1
                    this.actives = this.list[this.activeIndex];
                }
            }
            // 滚动位置
            let itemsArr = [...document.getElementsByClassName('items')];
            let list = document.getElementById('list');
            let offsetLeft = itemsArr[this.activeIndex].offsetLeft;
            list.scrollTo({left: offsetLeft - 2, top: 0, behavior: 'smooth'})
        },
        // 点击商品  弹出购买弹框
        async clickGoods(data){
            this.goodInfo = data;
            this.paymentShow = true;
            // 调用下单接口
            let obj = {
                modelId:this.modelId,
                imageId:this.goodInfo.id
            }
            let orderData = await orderConfirm({productItems:[obj]});
            this.taskId = orderData.data.taskId;
            this.setCommonData({
                key:'taskId',
                value:this.taskId,
            })
            this.orderNumber = orderData.data.tradeOrderNo;
            this.setCommonData({
                key:'orderNumber',
                value:this.orderNumber,
            })
            console.log(data);
            // 调用生成二维码接口
            let qrData = await orderSubmit({
                orderNo:orderData.data.payOrderNo,
                channelCode:'wx_native'
            });
            // this.qrCode = qrData.data.
            console.log(qrData)
            await this.generateQRCode(qrData.data.displayContent)
            // 轮询订单状态
            this.pollingState();
            this.interval = setInterval(()=>{
                this.pollingState();
            },1500)
        },
        // 轮询订单状态
        pollingState(){
            bodyEmitter(this.orderNumber).then(res=>{
                console.log(res)
                if(res.data.result == true){
                    // 清空定时器
                    clearInterval(this.interval)
                    // 设置支付状态
                    this.setCommonData({
                        key:'paymentStatus',
                        value:true,
                    })
                    this.$router.push('/modeSelect?taskId='+this.taskId)
                }
            })
        },
        // sse成功回调
        getbodyEmitter(){
            const ctrl = new AbortController(); // 用于中断请求
            let clientId = localStorage.getItem('clientId');
            fetchEventSource(process.env.VUE_APP_BASE_API + `/biz/order/bodyEmitter`, {  
                headers: {  
                    Authorization:'Bearer '+this.token,  // 你想通过 EventSource 请求发送的自定义头信息
                    clientId,
                },  
                method: 'GET', // SSE通常只支持GET，这里显式指定  
                signal: ctrl.signal,  
                openWhenHidden: true, // 页面退至后台时保持连接  
                onopen: (response) => {  
                    console.log('连接已打开', response);  
                },  
                onmessage: (event) => {  
                    console.log('收到消息:', event);  
                    setTimeout(()=>{
                        ctrl.abort(); 
                    },10000)
                },  
                onerror: (error) => {  
                    console.error('连接发生错误:', error);  
                    ctrl.abort(); // 中断请求  
                },  
                onclose: () => {  
                    console.log('连接已关闭');  
                },  
            })
        },
        // EventSource
        setEventSource(){
            const eventSource = new EventSource(process.env.VUE_APP_BASE_API+'/biz/order/bodyEmitter');
            eventSource.onmessage = function(event) {
                console.log('收到消息')
                console.log(event)
                // const messagesDiv = document.getElementById('messages');
                // messagesDiv.innerHTML += '<p>' + event.data + '</p >';
            };
            eventSource.onerror = (error) => {
                console.log('错误',error)
            };
            eventSource.onopen = (res) => {
                console.log('打开成功',res)
            }
        },
        // 支付成功回调
        paymentSuccess(){
            // 跳转拍照页面
            console.log(this.taskId)
            clearInterval(this.interval)
            // *****************不支付也可拍照代码***********************
            // this.setCommonData({
            //     key:'paymentStatus',
            //     value:true,
            // })
            // this.$router.push('/photograph?taskId='+this.taskId)
            // *****************不支付也可拍照代码***********************
        },
        sseConnect(){
            let that = this;
            let clientId = localStorage.getItem('clientId');
            const url=process.env.VUE_APP_BASE_API+'/resource/sse' //'https://localhost:6601/sse'
            const eventSource = new EventSourcePolyfill(
                url,
                {
                    headers: {
                        Authorization:'Bearer '+this.token,  // 你想通过 EventSource 请求发送的自定义头信息
                        clientId,
                    },
                }
            );
            /*
            * open：订阅成功（和后端连接成功）
            */
            eventSource.onopen = function (e) {
                console.log(e, "连接刚打开时触发");
            };
            /*
            * message：后端返回信息，格式可以和后端协商
            */

            eventSource.onmessage = function (e) {
                console.log(e,'后端返回信息，格式可以和后端协商');
                if(e.data){
                    // 关注成功
                    // 关闭链接
                    // eventSource.close();
                    that.$emit('update:isShow',false)
                    that.$emit('scanCodeEnd')
                }
                // const data = JSON.parse(e.data) || {};//这里后端返回的是字符串所以目前我这边有转换
            };
            /*
            * error：错误（可能是断开，可能是后端返回的信息）
            */
            eventSource.onerror = function (e) {
                console.log(e, "连接无法打开时触发");
                eventSource.close(); // 关闭连接
                    setTimeout(() => {
                }, 5000);
            };
        },
        // 同时后端返回订单状态
        notifyTheBackend(){
            sseResult(this.orderNumber).then(res=>{
                console.log(res);
            })
        },
        // 获取商品列表
        getprodList(){
            let obj = {
                pageNum:1,
                pageSize:10,
                modelId:this.modelId,
                status:0
            }
            prodList(obj).then(res=>{
                this.list = res.data.rows;
                this.actives = res.data.rows[0];
            })
        },
        // 点击退出登录
        exitBtn(){
            // 返回首页
            this.$router.push('/theme')
        },
        generateQRCode(url) {
            return new Promise((resolve,reject)=>{
                // 生成二维码逻辑(参数指定url文字即可)
                QRCode.toDataURL(url)
                .then(async (qr) => {
                    this.qrCode = qr;
                    resolve(qr)
                })
                .catch((error) => {
                    console.error("生成二维码出错：", error);
                    reject(error)
                });
            })
        },
    },
    mounted() {
        this.modelId = this.$route.query.modelId;
        this.title = this.$route.query.title;
        this.getprodList()
    },
    beforeDestroy(){
        clearInterval(this.interval)
    }
}
</script>

<style lang="less" scoped>
.goodList{
  width: 100%;
  height: 1920px;
  background-image: url('../assets/img/bgImg.png');
  background-size: 100% 1920px;
  position: relative;
//   overflow: hidden;
  display: flex;
  flex-direction: column;
  .headss{
    flex: none;
  }
  .exitBtn{
    width: 94px;
    height: 94px;
    position: fixed;
    left: 52px;
    top: 46px;
  }
  .conlist{
    flex: 1;
    padding: 0  50px  110px 50px;
    box-sizing: border-box;
    // overflow: hidden;
    display: flex;
    flex-direction: column;
    .mainBox{
        flex: 1;
        width: 100%;
        display: flex;
        align-items: center;
        padding-top: 216px;
        .btns{
            flex: none;
            margin-bottom: 280px;
            cursor: pointer;
            img{
                width: 120px;
                height: 120px;
            }
        }
        .mainImg{
            flex: 1;
            height: 100%;
            box-sizing: border-box;
            /deep/.el-carousel {
                height: 100%;
                .el-carousel__container {
                    height: 100%;
                    video{
                        width: 100%;
                        height: 100%;
                    }
                }
                .el-carousel__indicators{
                    display: none;
                }
                .el-carousel__arrow{
                    display: none;
                }
            }
            .imgBox{
                width: 550px;
                height: 744px;
                background: linear-gradient(180deg, #B0AEFF 0%, #FFC9EB 43.13%, #FFDEC0 100%);
                box-shadow: 8px 10px 10px 0px #03009233;
                box-sizing: border-box;
                border-radius: 4px;
                margin: 0 auto;
                padding: 6px;
                position: relative;
                margin-top: 30px;
                &::after{
                    content:'';
                    display: block;
                    width: 100%;
                    height: 100%;
                    background: linear-gradient(180deg, #B0AEFF 0%, #FFC9EB 43.13%, #FFDEC0 100%);
                    position: absolute;
                    border-radius: 4px;
                    left: 0;
                    top: 0;
                    padding: 6px;
                    z-index: -2;
                    box-sizing: border-box;
                    transform: rotate(-6deg);
                    box-shadow: 8px 10px 10px 0px #03009233;
                }
                &::before{
                    content:'';
                    display: block;
                    width: calc(100% - 12px);
                    height: calc(100% - 12px);
                    position: absolute;
                    background-color: #FFFFFF;
                    z-index: -1;
                    left: 6px;
                    top: 6px;
                    transform: rotate(-6deg);
                    border-radius: 4px;
                }
                img{
                    width: 100%;
                    height: 100%;
                    object-fit:cover;
                    vertical-align: bottom;
                    border-radius: 4px;
                }
            }
            .texts{
                // line-height: 48px;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-top: 33px;
                .name{
                    // width: 100%;
                    text-align: center;
                    font-size: 40px;
                    color: #7875FC;
                    display: flex;
                    align-items: center;
                    margin-right: 20px;
                    .ju{
                        width: 12px;
                        height: 12px;
                        background: linear-gradient(to bottom, #7875FC, #C4AAFF);
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin-right: 8px;
                        &::after{
                            width: 6px;
                            height: 6px;
                            content: '';
                            display: flex;
                            background: #FFFFFF;
                            border-radius: 50%;
                        }
                    }
                }
                .price{
                    // text-align: center;
                    // font-size: 48px;
                    // color: #7875FC;
                    // font-weight: bold;
                    font-size: 48px;
                    font-weight: bold;
                }
            }
            .toBuy{
                width: 250px;
                height: 80px;
                text-align: center;
                line-height: 80px;
                margin: 0 auto;
                margin-top: 16px;
                cursor: pointer;
                font-size: 32px;
                position: relative;
                &::before{
                    content:'';
                    display: block;
                    background-image: url('../assets/img/commonBtn.png');
                    background-size: 100% 80px;
                    position: absolute;
                    width: 240px;
                    height: 80px;
                    z-index: -1;
                }
                &::after{
                    content: '';
                    position: absolute;
                    top: -15px;//设置top,left,right,bottom大小来控制扩大的范围
                    left: -30px;
                    right: -30px;
                    bottom: -15px;
                }
            }
        }
    }
    .listBox{
        flex: none;
        width: 100%;
        height: 520px;
        .list{
            width: 100%;
            height: 100%;
            overflow-x: auto;
            white-space: nowrap;
            position: relative;
            .items{
                width: 253px;
                height: 100%;
                display: inline-block;
                margin-left: 48px;
                position: relative;
                cursor: pointer;
                &:first-child{
                    margin-left: 0;
                }
                .imgBox{
                    width: 100%;
                    height: 350px;
                    // border: 4px solid transparent;
                    // border-image: linear-gradient(180deg, #7875FC99, #FFCA9999) 1 1 round;
                    background: linear-gradient(180deg, #B0AEFF 0%, #FFC9EB 43.13%, #FFDEC0 100%);
                    padding: 6px;
                    box-shadow: 8px 10px 10px 0px #03008733;
                    box-sizing: border-box;
                    margin: 0 auto;
                    border-radius: 4px;
                    img{
                        width: 100%;
                        height: 100%;
                        object-fit:cover;
                        border-radius: 4px;
                        vertical-align: bottom;
                    }
                }
                .texts{
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-top: 18px;
                    .name{
                        font-size: 24px;
                        color: #7875FC;
                        text-align: center;
                        display: flex;
                        align-items: center;
                        .ju{
                            width: 8px;
                            height: 8px;
                            background: linear-gradient(to bottom, #7875FC, #C4AAFF);
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            margin-right: 8px;
                            &::after{
                                width: 4px;
                                height: 4px;
                                content: '';
                                display: flex;
                                background: #FFFFFF;
                                border-radius: 50%;
                            }
                        }
                    }
                    .price{
                        font-size: 24px;
                        color: #7875FC;
                        text-align: center;
                        font-weight: bold;
                        margin-left: 8px;
                    }
                }
                .sanjiao{
                    width: 34px;
                    height: 42px;
                    position: absolute;
                    bottom: 60px;
                    left: 0;
                    right: 0;
                    margin: 0 auto;
                    z-index: 99;
                }
            }
        }
    }
  }
}
</style>